package com.xiaozhi.iot.modules.device.controller;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.xiaozhi.common.utils.MapstructUtils;
import com.xiaozhi.module.iot.DTO.OtaDTO;
import com.xiaozhi.module.iot.entity.IotDevice;
import com.xiaozhi.module.iot.service.IIotDeviceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;

/**
 * @Author weirdor
 * @Description
 * @Date 2025/9/3 14:27
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RestController
@RequestMapping("/device")
public class DeviceController {

    private final IIotDeviceService deviceService;

    @PostMapping("/ota")
    public ResponseEntity<byte[]> ota(@Parameter(description = "设备ID") @RequestHeader("Device-Id") String deviceId,
                                      @RequestBody OtaDTO otaReq) {
          log.info("deviceId:{}", deviceId);
          log.info("otaReq:{}", otaReq);
          IotDevice device = MapstructUtils.convert(otaReq, IotDevice.class);
        log.info("设备信息：{}", JSONUtil.toJsonStr(device));
        // 获取设备ID (MAC地址)
        if (StrUtil.isNotEmpty(deviceId)) {
            deviceId = device.getBoardMac();
        }
        device.setDeviceId(deviceId);
        if (StrUtil.isEmpty(deviceId)) {
            return ResponseEntity.badRequest().body("设备ID不能为空".getBytes());
        }
        IotDevice iotDevice = deviceService.getById(deviceId);
        if (iotDevice == null) {
            log.info("设备不存在:{}", deviceId);
            deviceService.saveOrUpdate(device);
        }else {
            //创建设备
            deviceService.saveOrUpdate(device);
            Map<String, Object> responseData = new HashMap<>();
            Map<String, Object> firmwareData = new HashMap<>();
            Map<String, Object> serverTimeData = new HashMap<>();

            // 设置服务器时间
            long timestamp = System.currentTimeMillis();
            serverTimeData.put("timestamp", timestamp);
            serverTimeData.put("timezone_offset", 480);

            // 设置固件信息
            firmwareData.put("url", "http;//192.168.0.3/api/device/ota");
            firmwareData.put("version", "1.0.0");

            // 设置WebSocket连接信息.
            String websocketToken = "";//deviceService.generateToken(deviceId);
            Map<String, Object> websocketData = new HashMap<>();
            websocketData.put("url", "ws://192.168.0.3:3000");
            websocketData.put("token", websocketToken);
            responseData.put("websocket", websocketData);
            // 组装响应数据
            responseData.put("firmware", firmwareData);
            responseData.put("serverTime", serverTimeData);

            // 手动将响应数据转换为字节数组，以便设置确切的Content-Length
            byte[] responseBytes = StrUtil.bytes(JSONUtil.toJsonStr(responseData));
            // 使用ResponseEntity明确设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setContentLength(responseBytes.length);
            return new ResponseEntity<>(responseBytes, headers, HttpStatus.OK);
        }
        return ResponseEntity.ok().build();
    }


    @PostMapping("/ota/activate")
    @ResponseBody
    @Operation(summary = "查询OTA激活状态", description = "返回OTA激活状态")
    public ResponseEntity<String> otaActivate(
            @Parameter(name = "Device-Id", description = "设备唯一标识", required = true, in = ParameterIn.HEADER)
            @RequestHeader("Device-Id") String deviceId) {
        return ResponseEntity.ok("success");
    }
}
